package cc.fs.video.myvideoproject.utils

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import cc.fs.video.myvideoproject.beans.FileBean
import java.util.*

/**
 * Created by fostion on 2015/10/15.
 */
class DatabaseHelper {

    var context: Context ? = null
    var database: SQLiteDatabase? = null

    constructor(_context: Context) {
        context = _context
        initDatabase()
    }

    fun initDatabase() {
        database = context?.openOrCreateDatabase("data.db", Context.MODE_PRIVATE, null)

        if (!isTableExist("file_info")) {
            database?.execSQL("create table file_info(name TEXT NOT NULL , path TEXT NOT NULL PRIMARY KEY," + "category TEXT NOT NULL)")
        }
    }


    fun saveFile(file: FileBean) {
        val c = database?.rawQuery("select * from file_info where path='" + file.path + "'", null)

        val valuesUser = ContentValues()
        valuesUser.put("name", file.name)
        valuesUser.put("path", file.path)
        valuesUser.put("category", file.category)

        if (c?.count == 0) {
            database?.insert("file_info", "id", valuesUser)
        } else {
            database?.update("file_info", valuesUser, "path='" + file.path + "'", null)
        }
        c?.close()
    }

    fun getFiles(): ArrayList<FileBean> {
        val files = ArrayList<FileBean>()
        var c: Cursor ? = database?.rawQuery("select * from file_info", null)
        val index1 = c?.getColumnIndex("name") ?: 0
        val index2 = c?.getColumnIndex("path") ?: 1
        val index3 = c?.getColumnIndex("category") ?: 2
        c?.moveToFirst()
        while (!c!!.isAfterLast) {
            val fileBean = FileBean()
            fileBean.name = c?.getString(index1)
            fileBean.path = c?.getString(index2)
            fileBean.category = c?.getString(index3)
            files.add(fileBean)
            c?.moveToNext()
        }
        return files
    }

    fun removeFile(file: FileBean) {
        database?.delete("file_info", " path='" + file.path + "' ", null)
    }

    fun isTableExist(tableName: String): Boolean {
        var result = false;
        if (tableName == null) return result
        var cursor: Cursor? = null
        try {
            val sql = "select count(*) as c from sqlite_master where type ='table' and name ='" + tableName.trim() + "' "
            cursor = database?.rawQuery(sql, null)
            if (cursor!!.moveToNext()) {
                val count = cursor.getInt(0)
                if (count > 0) {
                    result = true
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return result
    }

    fun relaseDatabase(){
        database?.close()
    }

}